<template>
  <el-container class="home-container">
    <!-- 侧边栏 -->
    <el-aside width="200px">
      <div class="logo-container">
        <img src="../images/logo-透明.png" alt="logo" class="logo-image" />
      </div>
      <el-menu
        :default-active="$route.path"
        class="el-menu-vertical"
        background-color="#304156"
        text-color="#fff"
        active-text-color="#ff6b00">
        <el-menu-item index="/dashboard" @click="$router.push('/dashboard')">
          <i class="el-icon-s-home"></i>
          <span slot="title">首页</span>
        </el-menu-item>
        
        <el-submenu index="/users" v-if="userInfo.role === 'admin'">
          <template slot="title">
            <i class="el-icon-s-custom"></i>
            <span>用户管理</span>
          </template>
          <el-menu-item index="/users/list" @click="$router.push('/users/list')">用户列表</el-menu-item>
          <el-menu-item index="/users/roles" @click="$router.push('/users/roles')">角色管理</el-menu-item>
        </el-submenu>

        <el-submenu index="/products">
          <template slot="title">
            <i class="el-icon-s-goods"></i>
            <span>商品管理</span>
          </template>
          <el-menu-item index="/products/list" @click="$router.push('/products/list')">商品列表</el-menu-item>
          <el-menu-item index="/products/category" @click="$router.push('/products/category')">商品分类</el-menu-item>
        </el-submenu>

        <el-submenu index="/sales">
          <template slot="title">
            <i class="el-icon-s-data"></i>
            <span>销售管理</span>
          </template>
          <el-menu-item index="/sales/orders" @click="$router.push('/sales/orders')">订单列表</el-menu-item>
          <el-menu-item index="/sales/analysis" @click="$router.push('/sales/analysis')">销售分析</el-menu-item>
        </el-submenu>

        <el-submenu index="/inventory">
          <template slot="title">
            <i class="el-icon-s-shop"></i>
            <span>库存管理</span>
          </template>
          <el-menu-item index="/inventory/stock" @click="$router.push('/inventory/stock')">库存状态</el-menu-item>
          <el-menu-item index="/inventory/adjustment" @click="$router.push('/inventory/adjustment')">库存操作</el-menu-item>
        </el-submenu>
      </el-menu>
    </el-aside>

    <!-- 主要内容区 -->
    <el-container>
      <!-- 顶部导航栏 -->
      <el-header>
        <div class="header-left">
          <page-breadcrumb />
        </div>
        <div class="header-right">
          <el-dropdown trigger="click" @command="handleCommand">
            <div class="user-info">
              <i class="el-icon-user-solid"></i>
              <span class="username">{{ userInfo.username }}</span>
              <i class="el-icon-arrow-down el-icon--right"></i>
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="changePassword">
                <i class="el-icon-key"></i>修改密码
              </el-dropdown-item>
              <el-dropdown-item divided command="logout">
                <i class="el-icon-switch-button"></i>退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </el-header>

      <!-- 内容区 -->
      <el-main>
        <router-view></router-view>
      </el-main>
    </el-container>

    <!-- 全局按钮 -->
    <global-buttons />

    <!-- 修改密码对话框 -->
    <el-dialog
      :visible.sync="changePasswordDialogVisible"
      title="修改密码"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      custom-class="custom-dialog"
      center>
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordForm" label-width="100px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入原密码"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请确认新密码"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCloseChangePasswordDialog">取 消</el-button>
        <el-button type="primary" @click="handleChangePasswordConfirm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 退出登录对话框 -->
    <el-dialog
      :visible.sync="logoutDialogVisible"
      title="退出登录"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      custom-class="custom-dialog"
      center>
      <div class="logout-content">
        <i class="el-icon-warning-outline warning-icon"></i>
        <span>确认退出登录吗？</span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCloseLogoutDialog">取 消</el-button>
        <el-button type="primary" @click="handleLogoutConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>

<script>
import { changePassword } from '@/api/auth'
import { logout } from '@/api/user'
import GlobalButtons from '@/components/GlobalButtons.vue'
import PageBreadcrumb from '@/components/Breadcrumb.vue'

export default {
  name: 'HomeView',
  components: {
    GlobalButtons,
    'page-breadcrumb': PageBreadcrumb
  },
  data() {
    // 验证确认密码
    const validateConfirmPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    
    return {
      activeMenu: '1',
      userInfo: {
        username: '管理员',
        role: '',
        userId: '' // 确保userInfo中有userId字段，现在是String类型UUID格式
      },
      changePasswordDialogVisible: false,
      logoutDialogVisible: false,
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    handleCommand(command) {
      switch (command) {
        case 'changePassword':
          this.openChangePasswordDialog();
          break;
        case 'logout':
          this.openLogoutDialog();
          break;
      }
    },
    openChangePasswordDialog() {
      this.passwordForm = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      };
      this.changePasswordDialogVisible = true;
    },
    handleCloseChangePasswordDialog() {
      this.$refs.passwordForm.resetFields();
      this.changePasswordDialogVisible = false;
    },
    handleChangePasswordConfirm() {
      this.$refs.passwordForm.validate((valid) => {
        if (valid) {
          // 创建一个新对象，不包含confirmPassword字段，但包含userId
          const passwordData = {
            userId: this.userInfo.userId, // 添加userId字段
            oldPassword: this.passwordForm.oldPassword,
            newPassword: this.passwordForm.newPassword
          }
          
          // 调用修改密码接口
          changePassword(passwordData)
            .then(response => {
              if (response.code === 200) {
                this.$message({
                  message: response.message || '密码修改成功',
                  type: 'success'
                });
                this.handleCloseChangePasswordDialog();
                // 清除用户信息和token
                localStorage.removeItem('token');
                localStorage.removeItem('userInfo');
                // 延迟跳转到登录页，让用户看到成功提示
                setTimeout(() => {
                  this.$router.push('/user/login');
                }, 1500);
              } else {
                this.$message({
                  message: response.message || '密码修改失败，请重试',
                  type: 'error'
                });
              }
            })
            .catch(error => {
              console.error('修改密码失败:', error);
              this.$message({
                message: '密码修改失败，请重试',
                type: 'error'
              });
            });
        }
      });
    },
    openLogoutDialog() {
      this.logoutDialogVisible = true;
    },
    handleCloseLogoutDialog() {
      this.logoutDialogVisible = false;
    },
    handleLogoutConfirm() {
      // 调用后端退出登录接口
      logout()
        .then(response => {
          if (response.code === 200) {
            // 清除所有本地存储的用户相关信息
            localStorage.removeItem('token');
            localStorage.removeItem('userInfo');
            sessionStorage.clear(); // 清除会话存储
            
            // 重置用户状态
            this.userInfo = {
              username: '',
              role: '',
              userId: ''
            };
            
            this.$message.success('退出登录成功');
            
            // 确保清除完所有信息后再跳转
            setTimeout(() => {
              // 跳转到登录页
              this.$router.push('/user/login');
            }, 100);
          } else {
            this.$message.error(response.message || '退出失败，请重试');
          }
        })
        .catch(error => {
          console.error('退出登录失败:', error);
          // 即使请求失败，也清除本地信息并跳转
          localStorage.removeItem('token');
          localStorage.removeItem('userInfo');
          sessionStorage.clear();
          
          this.$message.error('退出失败，已清除本地登录信息');
          this.$router.push('/user/login');
        })
        .finally(() => {
          this.logoutDialogVisible = false;
        });
    }
  },
  mounted() {
    // 从localStorage获取用户信息
    const userInfo = localStorage.getItem('userInfo')
    if (userInfo) {
      try {
        const parsedUserInfo = JSON.parse(userInfo)
        this.userInfo = {
          ...this.userInfo,
          ...parsedUserInfo
        }
        
        // 确保userId存在，如果不存在则使用其他可用标识
        if (!this.userInfo.userId && parsedUserInfo.userId) {
          this.userInfo.userId = parsedUserInfo.userId;
        } else if (!this.userInfo.userId && parsedUserInfo.id) {
          // 向后兼容：如果没有userId但有id，使用id作为userId
          this.userInfo.userId = parsedUserInfo.id;
        }
        
        console.log('当前用户信息:', this.userInfo)
      } catch (error) {
        console.error('解析用户信息失败:', error)
      }
    }
  }
};
</script>

<style scoped>
.home-container {
  height: 100vh;
}

.el-aside {
  background-color: #304156;
}

.logo-container {
  height: 60px;
  padding: 10px 15px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  background-color: #304156;
  padding-left: 25%;
}

.logo-image {
  height: 50px;
  object-fit: contain;
}

.el-menu {
  border-right: none;
  margin-top: 10px;
}

/* 统一菜单项样式 */
.el-menu-item,
.el-submenu__title {
  font-size: 16px;
  height: 56px;
  line-height: 56px;
  padding-left: 20px !important;
  margin: 4px 0;
}

.el-menu-item i,
.el-submenu__title i {
  font-size: 24px;
  margin-right: 12px;
  width: 24px;
  text-align: center;
  color: #fff;
}

/* 子菜单项样式 */
.el-submenu .el-menu-item {
  font-size: 14px;
  height: 50px;
  line-height: 50px;
  padding-left: 61px !important;
  margin: 0;
}

/* 菜单项激活和悬停状态 */
.el-menu-item:focus,
.el-menu-item:hover,
.el-submenu__title:hover {
  background-color: #263445;
}

.el-menu-item.is-active {
  color: #ff6b00 !important;
  background-color: #263445;
}

/* 修改菜单激活颜色 */
.el-menu-vertical {
  background-color: #304156;
}

.el-menu-vertical:not(.el-menu--collapse) {
  width: 200px;
}

.el-menu--popup {
  background-color: #304156 !important;
}

.el-menu--popup .el-menu-item {
  color: #fff;
  background-color: #304156;
}

.el-menu--popup .el-menu-item:hover,
.el-menu--popup .el-menu-item:focus {
  background-color: #263445;
}

.el-menu--popup .el-menu-item.is-active {
  color: #ff6b00;
  background-color: #263445;
}

.el-header {
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 1px 4px rgba(0,21,41,.08);
  padding: 0 20px;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-right {
  display: flex;
  align-items: center;
}

.el-dropdown-link {
  cursor: pointer;
  color: #304156;
}

.el-button--text {
  color: #304156;
}

.el-button--text:hover,
.el-button--text:focus {
  color: #ff6b00;
}

.el-main {
  background-color: #f0f2f5;
  padding: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 0 12px;
  height: 40px;
  border-radius: 20px;
  transition: all 0.3s;
}

.user-info:hover {
  background: rgba(255, 107, 0, 0.1);
}

.user-info i.el-icon-user-solid {
  font-size: 20px;
  color: #304156;
  margin-right: 8px;
}

.user-info .username {
  font-size: 14px;
  color: #304156;
  margin-right: 4px;
}

.user-info i.el-icon--right {
  font-size: 12px;
  color: #304156;
  margin-left: 4px;
}

/* 下拉菜单样式 */
.el-dropdown-menu {
  padding: 5px 0 !important;
  border-radius: 4px !important;
}

.el-dropdown-menu__item {
  display: flex !important;
  align-items: center !important;
  padding: 8px 16px !important;
  font-size: 14px !important;
  color: #304156 !important;
  line-height: 1.5 !important;
  cursor: pointer !important;
}

.el-dropdown-menu__item i {
  margin-right: 8px !important;
  font-size: 16px !important;
  width: 16px !important;
  text-align: center !important;
}

.el-dropdown-menu__item:hover {
  background-color: rgba(255, 107, 0, 0.1) !important;
  color: #ff6b00 !important;
}

.el-dropdown-menu__item:hover i {
  color: #ff6b00 !important;
}

.el-dropdown-menu__item.el-dropdown-menu__item--divided {
  position: relative !important;
  margin-top: 6px !important;
  border-top: 1px solid #ebeef5 !important;
}

.el-dropdown-menu__item.el-dropdown-menu__item--divided:before {
  content: '' !important;
  height: 6px !important;
  display: block !important;
  margin: 0 !important;
  padding: 0 !important;
  overflow: hidden !important;
}

/* 对话框样式 */
.custom-dialog {
  border-radius: 8px !important;
  overflow: hidden !important;
}

.custom-dialog .el-dialog__header {
  padding: 20px !important;
  border-bottom: 1px solid #ebeef5 !important;
  background-color: #fff !important;
}

.custom-dialog .el-dialog__body {
  padding: 30px 20px !important;
  background-color: #fff !important;
}

.custom-dialog .el-dialog__footer {
  padding: 10px 20px 20px !important;
  text-align: right !important;
  background-color: #fff !important;
}

.custom-dialog .el-button--primary {
  background-color: #ff6b00 !important;
  border-color: #ff6b00 !important;
  border-radius: 4px !important;
}

.custom-dialog .el-button--primary:hover,
.custom-dialog .el-button--primary:focus {
  background-color: #ff8533 !important;
  border-color: #ff8533 !important;
}

.custom-dialog .el-button {
  border-radius: 4px !important;
}

.logout-content {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  padding: 20px 0 !important;
}

.warning-icon {
  font-size: 24px !important;
  color: #ff6b00 !important;
  margin-right: 10px !important;
}

.dialog-footer {
  text-align: right;
}
</style> 